package com.songlanyun.modules.offlineorderincome.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.DistributionConstant;
import com.songlanyun.common.enums.IntegralConstant;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.enums.OfflineOrderConstant;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserInfoEntity;
import com.songlanyun.modules.account.model.vo.AccountParentVO;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserInfoService;
import com.songlanyun.modules.applyareaagent.entity.ApplyAreaAgentEntity;
import com.songlanyun.modules.applyareaagent.service.ApplyAreaAgentService;
import com.songlanyun.modules.config.entity.ProfitSharingEntity;
import com.songlanyun.modules.config.service.ProfitSharingService;
import com.songlanyun.modules.integralrecord.entity.IntegralRecord;
import com.songlanyun.modules.integralrecord.service.IntegralRecordService;
import com.songlanyun.modules.offlineorder.entity.OfflineOrder;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.usergains.entity.UserOrderGains;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.offlineorderincome.dao.OfflineOrderIncomeDao;
import com.songlanyun.modules.offlineorderincome.entity.OfflineOrderIncome;
import com.songlanyun.modules.offlineorderincome.service.OfflineOrderIncomeService;


@Service("offlineOrderIncomeService")
public class OfflineOrderIncomeServiceImpl extends ServiceImpl<OfflineOrderIncomeDao, OfflineOrderIncome> implements OfflineOrderIncomeService {


    @Autowired
    private AccountService accountService;
    @Autowired
    private ProfitSharingService profitSharingService;

    @Autowired
    private ApplyAreaAgentService applyAreaAgentService;

    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public OfflineOrderIncome create(OfflineOrderIncome entity) {
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public OfflineOrderIncome modify(OfflineOrderIncome entity) {
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<OfflineOrderIncome> wrapper = new LambdaQueryWrapper<>();
        Long userId = MapUtil.getLong(params, "user_id");
        wrapper.eq(ObjectUtil.isNotNull(userId)&&userId>0,OfflineOrderIncome::getIncomeUserId,userId);
        wrapper.orderByDesc(OfflineOrderIncome::getCreateTime);
        IPage<OfflineOrderIncome> page = this.page(
                new Query<OfflineOrderIncome>().getPage(params),
                wrapper
        );

        page.getRecords().forEach(OfflineOrderIncome::loadOfflineOrder);


        return new PageUtils(page);
    }

    @Override
    public void income(OfflineOrder offlineOrder) {
        //消费线
        saleLineIncome(offlineOrder);

        //商家线
        shopLineIncome(offlineOrder);

    }

    /**
     * 消费者线
     * @param offlineOrder
     */
    private void saleLineIncome(OfflineOrder offlineOrder){
        Long userId = offlineOrder.getUserId();
        List<AccountParentVO> vos = accountService.getAllParentUser(userId);
        ProfitSharingEntity profitSharing = profitSharingService.info();
        int index = 0;
        BigDecimal headOfGroup = BigDecimal.ZERO;
        for (AccountParentVO vo : vos)
        {
            index++;
            if(index==1) {
                BigDecimal income = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getConsumerDirectPushReward().doubleValue()/100,8);
                OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, income, OfflineOrderConstant.IncomeType.DIRECT_PUSH_USER);

                IntegralRecord integralRecord = new IntegralRecord(vo.getId(), income, IntegralConstant.InnerMode.DIRECT_PUSH_USER,
                        IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "消费者直推奖励");
                integralRecordService.inner(integralRecord);
                continue;
            }

            if(index >1 && MemberConstant.MemberGrade.GROUP_HEAD.equals(vo.getGrade()) && headOfGroup.compareTo(BigDecimal.ZERO)==0)
            {

                headOfGroup = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getConsumerRegimentReward().doubleValue() / 100,8);
                if(headOfGroup.compareTo(BigDecimal.ZERO)>0) {
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, headOfGroup, OfflineOrderConstant.IncomeType.CONSUMER_REGIMENT);

                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), headOfGroup, IntegralConstant.InnerMode.CONSUMER_REGIMENT,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "消费者团长奖励");
                    integralRecordService.inner(integralRecord);
                }
                continue;
            }

            if(index > 1  && MemberConstant.MemberGrade.GROUP_HEAD.equals(vo.getGrade()) && headOfGroup.compareTo(BigDecimal.ZERO)>0)
            {

                BigDecimal gains = MathUtils.setScaleDown(headOfGroup.doubleValue() * profitSharing.getConsumerInterpositionRegimentReward().doubleValue() / 100,8);
                if(gains.compareTo(BigDecimal.ZERO)>0) {
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, gains, OfflineOrderConstant.IncomeType.CONSUMER_INTERPOSITION_REGIMENT);

                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), gains, IntegralConstant.InnerMode.CONSUMER_INTERPOSITION_REGIMENT,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "消费者间接团长奖励");
                    integralRecordService.inner(integralRecord);
                }
                break;
            }
        }

        for (AccountParentVO vo : vos) {
            ApplyAreaAgentEntity entity = applyAreaAgentService.loadByUserId(vo.getId());
            if(ObjectUtil.isNotNull(entity) && entity.getStatus()==1)
            {
                BigDecimal income = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getConsumerTerritorialReward().doubleValue()/100,8);
                if(income.compareTo(BigDecimal.ZERO)>0) {
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, income, OfflineOrderConstant.IncomeType.CONSUMER_TERRITORIAL);
                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), income, IntegralConstant.InnerMode.CONSUMER_TERRITORIAL,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "消费者属地分润奖励");
                    integralRecordService.inner(integralRecord);
                    break;
                }
            }
        }
    }




    /**
     * 商家线
     * @param offlineOrder
     */
    private void shopLineIncome(OfflineOrder offlineOrder){
        Long shopId = offlineOrder.getShopId();
        ShopEntity shopEntity = shopService.loadShopBy(shopId, false);
        if(ObjectUtil.isNull(shopEntity))
        {
            return ;
        }
        List<AccountParentVO> vos = accountService.getAllParentUser(shopEntity.getUserId());
        ProfitSharingEntity profitSharing = profitSharingService.info();
        int index = 0;
        BigDecimal headOfGroup = BigDecimal.ZERO;
        for (AccountParentVO vo : vos)
        {
            index++;
            if(index==1) {
                BigDecimal income = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getShopDirectPushReward().doubleValue()/100,8);
                OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, income, OfflineOrderConstant.IncomeType.SHOP_DIRECT_PUSH_USER);

                IntegralRecord integralRecord = new IntegralRecord(vo.getId(), income, IntegralConstant.InnerMode.SHOP_CONSUMER_TERRITORIAL,
                        IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "商家直推奖励");
                integralRecordService.inner(integralRecord);
                continue;
            }

            if(index >1 && MemberConstant.MemberGrade.GROUP_HEAD.equals(vo.getGrade()) && headOfGroup.compareTo(BigDecimal.ZERO)==0)
            {

                headOfGroup = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getShopRegimentReward().doubleValue() / 100,8);
                if(headOfGroup.compareTo(BigDecimal.ZERO)>0) {
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, headOfGroup, OfflineOrderConstant.IncomeType.SHOP_CONSUMER_REGIMENT);

                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), headOfGroup, IntegralConstant.InnerMode.SHOP_CONSUMER_REGIMENT,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "商家团长奖励");
                    integralRecordService.inner(integralRecord);
                }
                continue;
            }

            if(index > 1  && MemberConstant.MemberGrade.GROUP_HEAD.equals(vo.getGrade()) && headOfGroup.compareTo(BigDecimal.ZERO)>0)
            {

                BigDecimal gains = MathUtils.setScaleDown(headOfGroup.doubleValue() * profitSharing.getShopInterpositionRegimentReward().doubleValue() / 100,8);
                if(gains.compareTo(BigDecimal.ZERO)>0) {
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, gains, OfflineOrderConstant.IncomeType.SHOP_CONSUMER_INTERPOSITION_REGIMENT);

                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), gains, IntegralConstant.InnerMode.SHOP_CONSUMER_INTERPOSITION_REGIMENT,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "商家间接团长奖励");
                    integralRecordService.inner(integralRecord);
                }
                break;
            }
        }

        ApplyAreaAgentEntity entity = applyAreaAgentService.loadBy(shopEntity.getProvinceCode(), shopEntity.getCityCode(), shopEntity.getAreaCode());
        if(ObjectUtil.isNotNull(entity))
        {

            BigDecimal income = MathUtils.setScaleDown(offlineOrder.getShopConsumeIntegralAble().doubleValue() * profitSharing.getShopTerritorialReward().doubleValue()/100,8);
            if(income.compareTo(BigDecimal.ZERO)>0) {
                AccountEntity user = accountService.getUserById(entity.getUserId(), false);
                UserInfoEntity userInfoEntity = userInfoService.loadById(entity.getUserId(), false);
                if(ObjectUtil.isNotNull(user)) {
                    AccountParentVO vo = new AccountParentVO();
                    vo.setId(user.getId());
                    vo.setMobile(user.getMobile());
                    vo.setUsername(StringUtils.isNotEmpty(userInfoEntity.getRealName())?userInfoEntity.getRealName():userInfoEntity.getNickname());
                    vo.setRoleName(userInfoEntity.getRealName());
                    vo.setNickname(userInfoEntity.getNickname());
                    OfflineOrderIncome offlineOrderIncome = buildCreate(offlineOrder, vo, income, OfflineOrderConstant.IncomeType.SHOP_CONSUMER_TERRITORIAL);
                    IntegralRecord integralRecord = new IntegralRecord(vo.getId(), income, IntegralConstant.InnerMode.SHOP_CONSUMER_TERRITORIAL,
                            IntegralConstant.IntegralModelType.OFFLINE_ORDER_INCOME, offlineOrderIncome.getId(), "商家属地分润奖励");
                    integralRecordService.inner(integralRecord);
                }
            }
        }


    }


    private OfflineOrderIncome buildCreate(OfflineOrder offlineOrder, AccountParentVO vo, BigDecimal income,OfflineOrderConstant.IncomeType type) {
        OfflineOrderIncome build = OfflineOrderIncome.builder()
                .incomeUserId(vo.getId())
                .incomeUserMobile(vo.getMobile())
                .incomeUserName(StringUtils.isNoneEmpty(vo.getRealName()) ? vo.getRealName() : vo.getNickname())
                .offlineOrderId(offlineOrder.getId())
                .incomeType(type)
                .settlement(true)
                .incomePoint(income)
                .createTime(new Date())
                .build();
        this.create(build);
        return build;
    }
}
